package com.anssy.voteballot;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.anssy.voteballot.activity.TopicsListActivity;
import com.anssy.voteballot.base.BaseActivity;
import com.anssy.voteballot.bean.ContentRes;
import com.anssy.voteballot.bean.PushBean;
import com.anssy.voteballot.bean.SignRes;
import com.anssy.voteballot.bean.SignStatusRes;
import com.anssy.voteballot.bean.base.BaseRes;
import com.anssy.voteballot.constant.ConstantValue;
import com.anssy.voteballot.http.Api;
import com.anssy.voteballot.http.HttpService;
import com.anssy.voteballot.utils.CurrencyUtils;
import com.anssy.voteballot.utils.DeviceUtils;
import com.anssy.voteballot.utils.DownloadUtil;
import com.anssy.voteballot.utils.HttpUtils;
import com.anssy.voteballot.utils.VersionUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.yalantis.ucrop.util.BitmapLoadUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import cn.jpush.android.api.JPushInterface;
import okhttp3.ResponseBody;
import okhttp3.internal.Version;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends BaseActivity implements View.OnClickListener {


    private static final String TAG = MainActivity.class.getSimpleName();
    //	签到标记（1为设定签到开始，2为关闭签到，3为平板签到）
    private static final String START_SIGN = "1";
    private static final String CLOSE_SIGN = "2";
    private static final String SIGN_NOW = "3";
    private Button mBtnSignIn;
    private TextView mTvSignInNum;
    private LinearLayout mLlProgress;
    private ContentRes contentRes;
    private static final String USER_FLAG = "0";
    private TextView mTvSecondTitle;
    private TextView mTvTitle;
    private TextView mTvAddress;
    private TextView mTvTime;
    private TextView mTvDeviceId;
    private TextView mTvVersionCode;
    private TextView mTvJrhy;
    private String registrationID;
    private TextView mTvNetStatus;


    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
            LogUtils.v(TAG, "unRegisterEventBus");
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String message) {
        if (!TextUtils.isEmpty(message)) {
            PushBean pushBean = new Gson().fromJson(message, PushBean.class);
            if (pushBean != null && pushBean.getType() != null && pushBean.getMeettingId() != null) {
                if (pushBean.getType().equals("1")) {
                    requestRxPermissions();
                } else if (pushBean.getType().equals("2")) {
                    Intent intent = new Intent(MainActivity.this, TopicsListActivity.class);
                    intent.putExtra(ConstantValue.ID, Integer.parseInt(pushBean.getMeettingId()));
                    intent.putExtra(ConstantValue.MEETING_NUM, pushBean.getSum());
                    startActivity(intent);
                    finish();
                }
            }
        }
    }

    @Override
    public int setLayoutResource() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        mBtnSignIn = findViewById(R.id.btn_sign_in);
        mTvSignInNum = findViewById(R.id.tv_sing_in_num);
        mLlProgress = findViewById(R.id.ll_progress);
        mTvTitle = findViewById(R.id.tv_title);
        mTvSecondTitle = findViewById(R.id.tv_second_title);
        mTvAddress = findViewById(R.id.tv_address);
        mTvTime = findViewById(R.id.tv_time);
        mTvDeviceId = findViewById(R.id.tv_device_id);
        mTvVersionCode = findViewById(R.id.tv_version_code);
        mTvJrhy = findViewById(R.id.tv_jrhy);
        mTvNetStatus = findViewById(R.id.tv_net_status);
    }

    @Override
    public void initData() {
        setBottomData();
        requestRxPermissions();
    }

    @SuppressLint("SetTextI18n")
    private void setBottomData() {
        CurrencyUtils.checkNetStatus(mTvNetStatus);
        if (!TextUtils.isEmpty(VersionUtils.getVersion(MainActivity.this))) {
            mTvVersionCode.setText("版本号:v" + VersionUtils.getVersion(MainActivity.this));
        }
        mTvDeviceId.setText("设备ID:" + DeviceUtils.getUniqueId(MainActivity.this));
    }


    private void bindJgId() {
        registrationID = JPushInterface.getRegistrationID(MainActivity.this);
        LogUtils.v(TAG, "registrationID--" + registrationID);
        if (!TextUtils.isEmpty(registrationID)) {
            Api.getRetrofit().create(HttpService.class).bindJgId(DeviceUtils.getUniqueId(MainActivity.this), registrationID)
                    .enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                            BaseRes baseRes = HttpUtils.parseResponse(response, BaseRes.class);
                            if (baseRes != null) {
                                if (baseRes.getCode() == 200) {
                                    LogUtils.v(TAG, "极光ID绑定成功");
                                } else {
                                    ToastUtils.showShort(baseRes.getMsg());
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });
        } else {
            bindJgId();
        }
    }

    private void requestRxPermissions() {
        RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
        rxPermissions
                .request(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                .subscribe(granted -> {
                    if (granted) {
                        getDataFromServer();
                    } else {
                        ToastUtils.showShort("请在设置中授权");
                    }
                });
    }

    @SuppressLint("SetTextI18n")
    private void getDataFromServer() {

        Api.getRetrofit().create(HttpService.class).getContent(DeviceUtils.getUniqueId(this)).enqueue(new Callback<ResponseBody>() {
            @SuppressLint({"SetTextI18n", "UseCompatLoadingForDrawables"})
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                contentRes = (ContentRes) HttpUtils.parseResponse(response, ContentRes.class);
                if (contentRes != null) {
                    //	200 是主持端获取的需要开启的签到，300 已经开启的签到，
                    if (contentRes.getCode() == 200) {
                        bindJgId();
                        if (!TextUtils.isEmpty(contentRes.getDatas().getTitle())) {
                            mTvTitle.setText(contentRes.getDatas().getTitle());
                        }
                        if (!TextUtils.isEmpty(contentRes.getDatas().getSetFubiaoti())) {
                            mTvSecondTitle.setText("———" + contentRes.getDatas().getSetFubiaoti());
                        }

                        if (!TextUtils.isEmpty(contentRes.getDatas().getSetTime())) {
                            mTvTime.setText("时间:" + contentRes.getDatas().getSetTime());
                        }

                        if (!TextUtils.isEmpty(contentRes.getDatas().getSetAdd())) {
                            mTvAddress.setText("地点:" + contentRes.getDatas().getSetAdd());
                        }
                        if (contentRes.getThisState() == 1) {
                            mBtnSignIn.setText("发起签到");
                        } else if (contentRes.getThisState() == 2) {
                            mBtnSignIn.setText("未开启签到");
                        }

                    } else if (contentRes.getCode() == 300) {
                        bindJgId();
                        if (!TextUtils.isEmpty(contentRes.getDatas().getTitle())) {
                            mTvTitle.setText(contentRes.getDatas().getTitle());
                        }
                        if (!TextUtils.isEmpty(contentRes.getDatas().getSetFubiaoti())) {
                            mTvSecondTitle.setText("———" + contentRes.getDatas().getSetFubiaoti());
                        }

                        if (!TextUtils.isEmpty(contentRes.getDatas().getSetTime())) {
                            mTvTime.setText("时间:" + contentRes.getDatas().getSetTime());
                        }

                        if (!TextUtils.isEmpty(contentRes.getDatas().getSetAdd())) {
                            mTvAddress.setText("地点:" + contentRes.getDatas().getSetAdd());
                        }
                        if (contentRes.getThisState() == 1) {
                            mBtnSignIn.setText("停止签到");
                        } else if (contentRes.getThisState() == 2) {
                            getSignStatus(contentRes.getDatas().getId());
                        }
                    } else if (contentRes.getCode() == 600) {
                        bindJgId();
                        if (!TextUtils.isEmpty(contentRes.getDatas().getTitle())) {
                            mTvTitle.setText(contentRes.getDatas().getTitle());
                        }
                        if (!TextUtils.isEmpty(contentRes.getDatas().getSetFubiaoti())) {
                            mTvSecondTitle.setText("———" + contentRes.getDatas().getSetFubiaoti());
                        }

                        if (!TextUtils.isEmpty(contentRes.getDatas().getSetTime())) {
                            mTvTime.setText("时间:" + contentRes.getDatas().getSetTime());
                        }

                        if (!TextUtils.isEmpty(contentRes.getDatas().getSetAdd())) {
                            mTvAddress.setText("地点:" + contentRes.getDatas().getSetAdd());
                        }
                        if (contentRes.getThisState() == 1) {
                            mBtnSignIn.setText("发起签到");
                        } else {
                            mBtnSignIn.setText("未开启签到");
                            mBtnSignIn.setBackground(getResources().getDrawable(R.drawable.bg_circle_default));
                            ToastUtils.showShort("未开启签到");
                        }
                    } else {
                        mBtnSignIn.setText("");
                        ToastUtils.showLong(contentRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                t.printStackTrace();
            }
        });
    }

    private void getSignStatus(Integer id) {
        Api.getRetrofit().create(HttpService.class).getSignStatus(DeviceUtils.getUniqueId(this), id).enqueue(new Callback<ResponseBody>() {
            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                SignStatusRes signStatusRes = (SignStatusRes) HttpUtils.parseResponse(response, SignStatusRes.class);
                if (signStatusRes != null && signStatusRes.getCode() == 400 && signStatusRes.getThisState() == 2) {
                    mBtnSignIn.setText("已签到");
                    mBtnSignIn.setClickable(false);
                    mBtnSignIn.setBackground(getResources().getDrawable(R.drawable.bg_circle_default));
                } else {
                    mBtnSignIn.setBackground(getResources().getDrawable(R.drawable.bg_circle));
                    mBtnSignIn.setText("签到");
                }
            }

            @Override
            public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                t.printStackTrace();
            }
        });
    }

    @Override
    public void initListener() {
        mTvDeviceId.setOnClickListener(this);
        mBtnSignIn.setOnClickListener(this);
        mTvJrhy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (contentRes != null && contentRes.getDatas() != null && contentRes.getDatas().getId() != null) {
                    if (contentRes.getCode() == 200 || contentRes.getCode() == 300) {
                        Intent intent = new Intent(MainActivity.this, TopicsListActivity.class);
                        intent.putExtra(ConstantValue.ID, contentRes.getDatas().getId());
                        startActivity(intent);
                    }
                }
            }
        });

    }

    @SuppressLint({"UseCompatLoadingForDrawables", "NonConstantResourceId"})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.tv_device_id:
                if (CurrencyUtils.copyStr(MainActivity.this, DeviceUtils.getUniqueId(MainActivity.this))) {
                    ToastUtils.showShort("复制成功");
                }
                break;

            case R.id.btn_sign_in:
                if (mBtnSignIn.getText().toString().trim().equals("发起签到")) {
                    toSign(START_SIGN);
                } else if (mBtnSignIn.getText().toString().trim().equals("签到")) {
                    toSign(SIGN_NOW);
                } else if (mBtnSignIn.getText().toString().trim().equals("已签到")) {
                    mBtnSignIn.setBackground(getResources().getDrawable(R.drawable.bg_circle));
                    mTvSignInNum.setVisibility(View.VISIBLE);
                } else if (mBtnSignIn.getText().toString().trim().equals("停止签到")) {
                    toSign(CLOSE_SIGN);
                }
                break;

            default:
                break;
        }
    }

    private void toSign(String signFlag) {
        mLlProgress.setVisibility(View.VISIBLE);
        Api.getRetrofit().create(HttpService.class).signIn(DeviceUtils.getUniqueId(this), contentRes.getDatas().getId(), signFlag).enqueue(new Callback<ResponseBody>() {
            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                mLlProgress.setVisibility(View.GONE);
                SignRes signRes = (SignRes) HttpUtils.parseResponse(response, SignRes.class);
                if (signRes != null) {
                    if (signRes.getCode() == 200) {
                        if (signFlag.equals(START_SIGN)) {
                            mBtnSignIn.setText("停止签到");
                            mBtnSignIn.setBackground(getResources().getDrawable(R.drawable.bg_circle));
                        } else if (signFlag.equals(SIGN_NOW)) {
                            mBtnSignIn.setText("已签到");
                            mBtnSignIn.setClickable(false);
                            mBtnSignIn.setBackground(getResources().getDrawable(R.drawable.bg_circle_default));
                        } else if (signFlag.equals(CLOSE_SIGN)) {
                            mBtnSignIn.setBackground(getResources().getDrawable(R.drawable.bg_circle));
                            mBtnSignIn.setText("发起签到");
                        }
                    } else {
                        ToastUtils.showShort(signRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                mLlProgress.setVisibility(View.GONE);
                t.printStackTrace();
            }
        });
    }


}